from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect, get_object_or_404

from .models import User
from .forms import UserForm, ChangePasswordForm, LoginForm
from .mylogin_utils import my_login_required, my_login_admin_required


@my_login_admin_required
@my_login_required
def user_list(request):
    users = User.objects.all()
    return render(request, 'mainapp/users/user_list.html', {'users': users})


@my_login_admin_required
@my_login_required
def add_user(request):
    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('user_list')
    else:
        form = UserForm()
    return render(request, 'mainapp/users/user_form.html', {'form': form})


@my_login_admin_required
@my_login_required
def delete_user(request, user_id):
    user = get_object_or_404(User, id=user_id)
    user.delete()
    return redirect('user_list')


@my_login_admin_required
@my_login_required
def confirm_delete_user(request, user_id):
    user = get_object_or_404(User, id=user_id)
    if request.method == 'POST':
        user.delete()
        return redirect('user_list')
    return render(request, 'mainapp/users/confirm_delete.html', {'user': user})


@my_login_admin_required
@my_login_required
def change_password(request, user_id):
    user = get_object_or_404(User, id=user_id)
    if request.method == 'POST':
        form = ChangePasswordForm(request.POST)
        if form.is_valid():
            user.password = form.cleaned_data['password']
            user.role = form.cleaned_data['role']
            user.save()
            return redirect('user_list')
    else:
        form = ChangePasswordForm(initial={'role': user.role})
    return render(request, 'mainapp/users/change_password.html', {'form': form, 'user': user})


def login_view(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = User.objects.filter(username=username, password=password).first()
            if user:
                request.session['username'] = user.username
                request.session['role'] = user.role
                return redirect('user_list')
            else:
                form.add_error(None, "用户名或密码错误")
    else:
        form = LoginForm()
    return render(request, 'mainapp/users/login.html', {'form': form})


@my_login_admin_required
def logout_view(request):
    if 'username' in request.session:
        del request.session['username']
    if 'role' in request.session:
        del request.session['role']
    return redirect('login')
